package com.hxk.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import redis.clients.jedis.JedisPoolConfig;

/**
 * springboot整合spring data redis配置类
 * @author Cactus
 */
@Configuration
public class RedisConfig {

	/**
	 * 配置jedis配置连接池
	 * @ConfigurationProperties(prefix="redis.pool")
	 * 给注解使用springboot全局配置文件（application.properties）获取配置信息
	 * prefix前缀 
	 * 比如redis.pool.max-idle则表示配置最大空闲数
	 */
	@Bean
	@ConfigurationProperties(prefix="spring.redis.pool")
	public JedisPoolConfig newJedisPoolConfig() {
		JedisPoolConfig config = new JedisPoolConfig();
		//不在springboot全局配置文件中配置时，必须进行以下配置,如果使用了@ConfigurationProperties获取配置信息，则以下内容不比配置
		//最大空闲数
		//config.setMaxIdle(15);
		//最小空闲数
		//config.setMinIdle(10);
		//最大连接数
		//config.setMaxTotal(20);
		return config;
	}
	
	/**
	 * 配置jedis工厂类
	 */
	@Bean
	@ConfigurationProperties(prefix="spring.redis")
	public JedisConnectionFactory newJedisConnectionFactory(JedisPoolConfig poolConfig) {
		JedisConnectionFactory factory = new JedisConnectionFactory();
		//关联链接池的配置对象
		factory.setPoolConfig(poolConfig);
		//主机地址
		//factory.setHostName("127.0.0.1");
		//端口
		//factory.setPort(6379);
		
		return factory;
	}
	
	/**
	 * 创建redisTemplate
	 */
	@Bean
	public RedisTemplate<String, Object> newRedisTemplate(JedisConnectionFactory connectionFactory){
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		//关联JedisConnectionFactory
		template.setConnectionFactory(connectionFactory);
		//设置默认key序列化器
		template.setKeySerializer(new StringRedisSerializer());
		//设置默认val序列化器
		template.setValueSerializer(new StringRedisSerializer());
		
		return template;
	}
}
